package com.qiu.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.qiu.demo.entity.dto.LoginDto;
import com.qiu.demo.util.CaptchaUtils;
import com.qiu.demo.util.JsonResult;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Resource
    private CaptchaUtils captchaUtils;

    @GetMapping("/getCode")
    public void generateCaptcha(HttpServletResponse response) throws IOException {
        // 生成一个唯一的Key（可以使用UUID或用户Session ID）
        String captchaKey = "captcha:" + System.currentTimeMillis();

        // 生成验证码图片并写入响应流F
        captchaUtils.generateCaptcha(captchaKey, response);
    }

    @PostMapping("/login")
    public JsonResult login(@RequestBody LoginDto loginDto) {
        // 验证验证码
        if (!captchaUtils.validateCaptcha(loginDto.getCaptchaKey(), loginDto.getCaptcha())) {
            return JsonResult.error().codeAndMessage(400, "验证码错误"); // 验证码错误
        }
        captchaUtils.clearCaptcha(loginDto.getCaptchaKey());

        return JsonResult.success().codeAndMessage(200, "登录成功");
    }

    @PostMapping("/reg")
    public JsonResult reg(@RequestBody LoginDto loginDto) {

        // 验证验证码
        if (!captchaUtils.validateCaptcha(loginDto.getCaptchaKey(), loginDto.getCaptcha())) {
            return JsonResult.error().codeAndMessage(400, "验证码错误"); // 验证码错误
        }
        captchaUtils.clearCaptcha(loginDto.getCaptchaKey());

        return JsonResult.success().codeAndMessage(200, "注册成功");
    }

}
